package rss;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.attachment.Attachment;
import com.gargoylesoftware.htmlunit.attachment.CollectingAttachmentHandler;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class URLdownloader {

	URLdownloader() {

	}

	public boolean download(String url, String anchorName, String filepath) {

		boolean result = false;
		String myURL1 = url;
		String anchor_text = anchorName;
		String OutputFP = filepath;

		try {
			WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_8);
			webClient.setJavaScriptEnabled(false);
			webClient.setCssEnabled(false);
			webClient.setTimeout(120000); // 2 minutes

			HtmlPage page;
			page = webClient.getPage(myURL1);

			List<HtmlAnchor> anchors1 = page.getAnchors();
			HtmlAnchor download_link = null;

			for (HtmlAnchor anchor : anchors1) {
				if (anchor.asText().indexOf(anchor_text) > -1) {
					download_link = anchor;
					break;
				}
			}

			// System.out.println(">>>>>" + download_link.getAttribute("href"));

			final Page clickResult = download_link.click();
			final List<Attachment> attachments = new ArrayList<Attachment>();
			webClient.setAttachmentHandler(new CollectingAttachmentHandler(attachments));

			final WebResponse attachmentResponse = clickResult.getWebResponse();
			final InputStream attachmentStream = attachmentResponse.getContentAsStream();

			OutputStream out = new FileOutputStream(OutputFP);

			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = attachmentStream.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			attachmentStream.close();
			out.flush();
			out.close();

			attachments.clear();
			clickResult.cleanUp();

			webClient.closeAllWindows();
			webClient = null;
			
			result = true;

		} catch (FailingHttpStatusCodeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//System.out.println(":: CLOSE Browser ~~~~~~~~~~~~~~~~~~~~~~~~");
		return result;
	}

}
